/*
 * 文 件 名:  CreateInfoInterceptor
 * 版    权:
 * 描    述:  <描述>
 * 修 改 人:  RedName
 * 修改时间:  2022/5/16
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.zj003.framework.plugin;

import com.zj003.common.constant.ActionType;
import com.zj003.common.core.base.BaseEntity;
import com.zj003.common.util.SecurityUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * <功能详细描述>
 * 补充创新信息插件
 *
 * @author ReaName
 * @version [版本号, 2022/5/16]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
@Component
public class CreateInfoInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        //获取映射的信息
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];

        //获取sql类型
        String actionName = mappedStatement.getSqlCommandType().name().toUpperCase();

        Object object = invocation.getArgs()[1];

        if (object instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) object;
            if (actionName.equals(ActionType.INSERT)) {
                entity.setCreateBy(SecurityUtils.getUsername());
                entity.setCreateTime(new Date());
                entity.setUpdateBy(SecurityUtils.getUsername());
                entity.setUpdateTime(new Date());
            }
            else if (actionName.equals(ActionType.UPDATE)) {
                entity.setUpdateBy(SecurityUtils.getUsername());
                entity.setUpdateTime(new Date());
            }
            else if (actionName.equals(ActionType.DELETE)) {
                entity.setUpdateBy(SecurityUtils.getUsername());
                entity.setUpdateTime(new Date());
            }

        }

        return invocation.proceed();
    }
}
